
import { Control, FabricImage } from "fabric";
import { isUndefined } from 'lodash';
import FabricImg from "./FabricImg";

// 旋转控制器

class BrContorls extends Control {

    constructor(options) {
        super(options);
    }

    icon: FabricImg;

    x = 0.5;
    y = 0.5;
    cursorStyle = 'crosshair';
    actionHandler = (eventData, transform, x, y) => {
        const target = transform.target;
        const center = target.getCenterPoint();

        // 计算旋转角度（基于鼠标位置）
        const angleRad = Math.atan2(y - center.y, x - center.x) - ((Math.atan(target.height / target.width) - (Math.PI / 4)));

        let angle = (angleRad * 180 / Math.PI) - 45;
        angle = (angle + 360) % 360;
        // 吸附计算 距离目标角度差3度以内时才吸附  吸附的角度是 0 45 90 135 180 225 270 315 360
        const targetAngle = [0, 45, 90, 135, 180, 225, 270, 315, 360].find((targetAngle) => {
            return Math.abs(angle - targetAngle) < 6;
        });
        // 调整初始角度偏移‌:ml-citation{ref="2" data="citationList"}
        target.set('angle', isUndefined(targetAngle) ? angle : targetAngle);
        // 计算等比缩放比例（基于距离）
        const newDistance = Math.sqrt(Math.pow(x - center.x, 2) + Math.pow(y - center.y, 2));
        const originDistance = Math.sqrt(Math.pow(target.width / 2, 2) + Math.pow(target.height / 2, 2));
        const scale = newDistance / originDistance;
        target.set({
            scaleX: scale,
            scaleY: scale, // 强制等比缩放
        });

        return true;
    }

    render(ctx, left, top, styleOverride, fabricObject) {
        if (this.icon) {
            this.icon.set({
                originX: "center",
                originY: "center",
                left,
                top,
                // angle: fabricObject.angle
            });
            this.icon.render(ctx);
        }
    }



}

const brContorls = new BrContorls({});

export default brContorls;
